<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use think\Db;
use app\common\service\Material as MaterialService;
use app\common\service\Order as OrderService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\OrderMaterialItem as OrderMaterialItemService;
use app\common\service\CheckclothShrink as CheckclothShrinkService;
use app\common\service\Rejects as RejectsService;
use app\common\service\MaterialReturn as MaterialReturnService;

/**
 * 验布
 *
 */
class Checkcloth extends Admin {

	public function initialize() {
		parent::initialize();
	}

	/**
	 * 验布区主页
	 */
	public function index() {
		$assign = [
			'rejectsKV' => getRejectsKV(),
		];
		$assign['rejectsCount'] = count($assign['rejectsKV']);
		return $this->assign($assign)->fetch();
	}

	/**
	 * 次品退料
	 *
	 * @author KING
	 * @date 2020年4月24日
	 *
	 */
	public function rejects() {
		$isReturn = $this->request->param('is_return/d', 0);
		$clientOrdernum = $this->request->param('client_ordernum');
		$materialId = $this->request->param('material_id/d', 0);
		$clothNum = $this->request->param('cloth_num/d', 0);
		$length = $this->request->param('length/d', 0);
		$trueFabricWidth = $this->request->param('true_fabric_width/d', 0);
        if (substr($clientOrdernum, 0, 1) == 'B') {
            return $this->rejects_stock_m_type_1();
        }

		$orderService = new OrderService();
		$materialService = new MaterialService();
		$rejectsService = new RejectsService();
		$orderMaterialService = new OrderMaterialService();
		$orderMaterialItemService = new OrderMaterialItemService();
		$checkclothShrinkService = new CheckclothShrinkService();
		$orderInfo = $orderService->getInfoByClientOrdernum($clientOrdernum);

		if (!$orderInfo) {
			return $this->Json(0, '订单号不存在！');
		}
		$orderId = $orderInfo['id'];

		if (empty($materialId)) {
			return $this->Json(0, '未选择面料！');
		}

		if (empty($clothNum) || !is_numeric($clothNum)) {
			return $this->Json(0, '布号错误！');
		}

		if ($length > 300 || $length < 1) {
			return $this->Json(0, '验布米长范围只能是1-300！');
		}
		if ($trueFabricWidth > config('mp.fabric_width_max') || $trueFabricWidth < config('mp.fabric_width_min')) {
			return $this->Json(0, '实量布封范围只能是'.config('mp.fabric_width_min').'-'.config('mp.fabric_width_max').'！');
		}

		$rejectsIds = $this->request->param('rejects_id/a', []);
		$rejectsLength = $this->request->param('rejects_length/d', 0);
		if (empty($rejectsIds)) {
			return $this->Json(0, '请选择次品类型！');
		}
		if ($rejectsLength == '' || !is_numeric($rejectsLength)) {
			return $this->Json(0, '请填写次品米数！');
		}

		// 是否已退料
		$info = db('checkcloth_shrink')->where("order_id = {$orderInfo['id']} and material_id = {$materialId} and cloth_num = {$clothNum} and is_return = 1")->findOrEmpty();
		if ($info) {
			return $this->Json(0, '该物料布号已退料！');
		}

		$info = db('checkcloth_shrink')->where("order_id = {$orderInfo['id']} and material_id = {$materialId} and cloth_num = {$clothNum} and type = 1")->findOrEmpty();
		if ($info) {
			return $this->Json(0, '该物料布号已处理！');
		}
		$orderMaterialItemId = $orderMaterialItemService->getIdByClothNum($orderId, $materialId, $clothNum);
		if (!$orderMaterialItemId) {
			return $this->Json(0, '布号数据错误！');
		}
		$omiInfo = $orderMaterialItemService->getInfoById($orderMaterialItemId);
        if ($omiInfo['flag_del'] == 1) {
            return $this->Json(0, '此布号已删除！');
        }
		try {
			db()->startTrans();

			$insData = [
				'order_id' => $orderId,
				'client_ordernum' => $clientOrdernum,
				'type' => 1,
				'order_material_item_id' => $orderMaterialItemId,
				'cloth_num' => $clothNum,
				'material_id' => $materialId,
				'stalls_id' => arrayGet($omiInfo, 'stalls_id', 0),
				'length' => $length,
				'true_fabric_width' => $trueFabricWidth,
				'is_return' => 1,
				'is_rejects' => 1,
				'rejects_ids' => implode(',', $rejectsIds),
				'rejects_length' => round($rejectsLength, 2),
				'admin_id' => ADMIN_ID,
				'create_time' => time(),
				'update_time' => time(),
			];
			$checkclothShrinkId = db('checkcloth_shrink')->insertGetId($insData);

			// 标记退料
			if ($orderMaterialItemId) {
				$omiData = [
					'checkcloth_id' => $checkclothShrinkId,
					'is_return' => 1,
					'is_checkcloth' => 1,
					'checkcloth_time' => time(),
					'update_time' => time()
				];
				db('order_material_item')->where('id', $orderMaterialItemId)->update($omiData);
			}

			$omInfo = $orderMaterialService->getInfoByOrderIdMaterialId($orderId, $materialId);
            if ($omInfo){
                $upData = [
                    'return_notconfirm' => 1, //用于标记[待退料审核标记]
                    'update_time' => time(),
                ];
                db('order_material')->where('mid', $omInfo['mid'])->update($upData);
            }
			// 扣除条数(20200928修改为在 退料进度 确认退料后扣除条数)
			/* if ($omInfo && $omInfo['tiaoshu'] > 0) {
				$omData = [
					'tiaoshu' => $omInfo['tiaoshu']-1,
					'shiji_caigou_count' => $omInfo['tiaoshu']-1,
					'tiaoshu_detail' => $omInfo['tiaoshu_detail'] . '-1',
				];
				db('order_material')->where(['order_id' => $orderId, 'material_id' => $materialId])->update($omData);
			} */

			//同步到采购备忘
			$materialInfo = $materialService->getInfoById($materialId, 'name');
			$memoData = [
				'order_id' => $orderInfo['id'],
				'client_ordernum' => $clientOrdernum,
				'content' => "物料[".$materialInfo['name']."]验布区布号[{$clothNum}]次品退料{$rejectsLength}米（".implode(',', $rejectsIds)."）",
				'status' => 0,
				'create_time' => time(),
				'update_time' => time(),
			];
			db('memo')->insertGetId($memoData);

			// 同步到退料进度表里
			$mrData = [
				'material_id' => $materialId,
				'order_id' => $orderId,
				'client_ordernum' => $clientOrdernum,
				'order_material_id' => $omInfo['mid'],
				'order_material_item_id' => $orderMaterialItemId,
				'cloth_num' => $clothNum,
				'type' => 1,
				'reason' => implode(',', $rejectsIds),//$rejectsService->getNameStr($rejectsIds)
				'admin_id' => ADMIN_ID,
				'is_reduce' => 0,
				'status' => 0,
				'create_time' => time(),
				'update_time' => time(),
			];
			$materialReturnId = db('material_return')->insertGetId($mrData);

			// 记录退料操作日志
			(new MaterialReturnService())->addLog($materialReturnId, 1);

			// 更新布号米长
			$orderMaterialItemService->updateLength($orderId, $materialId);

			// 同步数据
			$checkclothShrinkService->syncData($orderId, $materialId,0);

			$this->addOrderLog($orderId, $clientOrdernum, $memoData['content']);
			db()->commit();
			return $this->Json(1, '添加次品退料信息 ID' . $checkclothShrinkId . ' 成功');
		} catch (\Exception $e) {
			db()->rollback();
			return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
		}
	}

	private function rejects_stock_m_type_1(){
        $isReturn = $this->request->param('is_return/d', 0);
        $clientOrdernum = $this->request->param('client_ordernum');
        $materialId = $this->request->param('material_id/d', 0);
        $clothNum = $this->request->param('cloth_num/d', 0);
        $length = $this->request->param('length/d', 0);
        $trueFabricWidth = $this->request->param('true_fabric_width/d', 0);

        $orderService = new OrderService();
        $materialService = new MaterialService();
        $rejectsService = new RejectsService();
        $orderMaterialService = new OrderMaterialService();
        $orderMaterialItemService = new OrderMaterialItemService();
        $checkclothShrinkService = new CheckclothShrinkService();

        $omInfo = $orderMaterialService->getInfoById(substr($clientOrdernum, 1, 10));
        if (!$omInfo) {
            return $this->Json(0, '采购批号不存在！');
        }

        if (empty($materialId)) {
            return $this->Json(0, '未选择面料！');
        }

        if (empty($clothNum) || !is_numeric($clothNum)) {
            return $this->Json(0, '布号错误！');
        }

        if ($length > 300 || $length < 1) {
            return $this->Json(0, '验布米长范围只能是1-300！');
        }
        if ($trueFabricWidth > config('mp.fabric_width_max') || $trueFabricWidth < config('mp.fabric_width_min')) {
            return $this->Json(0, '实量布封范围只能是'.config('mp.fabric_width_min').'-'.config('mp.fabric_width_max').'！');
        }

        $rejectsIds = $this->request->param('rejects_id/a', []);
        $rejectsLength = $this->request->param('rejects_length/d', 0);
        if (empty($rejectsIds)) {
            return $this->Json(0, '请选择次品类型！');
        }
        if ($rejectsLength == '' || !is_numeric($rejectsLength)) {
            return $this->Json(0, '请填写次品米数！');
        }

        // 是否已退料
        $info = db('checkcloth_shrink')->where("order_material_id = {$omInfo['mid']} and cloth_num = {$clothNum} and is_return = 1")->findOrEmpty();
        if ($info) {
            return $this->Json(0, '该物料布号已退料！');
        }

        $info = db('checkcloth_shrink')->where("order_material_id = {$omInfo['mid']} and cloth_num = {$clothNum} and type = 1")->findOrEmpty();
        if ($info) {
            return $this->Json(0, '该物料布号已处理！');
        }
        $orderMaterialItemId = $orderMaterialItemService->getIdByClothNum(0, 0, $clothNum, $omInfo['mid']);
        if (!$orderMaterialItemId) {
            return $this->Json(0, '布号数据错误！');
        }
        $omiInfo = $orderMaterialItemService->getInfoById($orderMaterialItemId);
        if ($omiInfo['flag_del'] == 1) {
            return $this->Json(0, '此布号已删除！');
        }
        try {
            db()->startTrans();

            $insData = [
                'order_id' => 0,
                'client_ordernum' => '',
                'stock_m_type'=>1,
                'order_material_id'=>$omInfo['mid'],
                'type' => 1,
                'order_material_item_id' => $orderMaterialItemId,
                'cloth_num' => $clothNum,
                'material_id' => $materialId,
                'stalls_id' => arrayGet($omiInfo, 'stalls_id', 0),
                'length' => $length,
                'true_fabric_width' => $trueFabricWidth,
                'is_return' => 1,
                'is_rejects' => 1,
                'rejects_ids' => implode(',', $rejectsIds),
                'rejects_length' => round($rejectsLength, 2),
                'admin_id' => ADMIN_ID,
                'create_time' => time(),
                'update_time' => time(),
            ];
            $checkclothShrinkId = db('checkcloth_shrink')->insertGetId($insData);

            // 标记退料
            if ($orderMaterialItemId) {
                $omiData = [
                    'checkcloth_id' => $checkclothShrinkId,
                    'is_return' => 1,
                    'is_checkcloth' => 1,
                    'checkcloth_time' => time(),
                    'update_time' => time()
                ];
                db('order_material_item')->where('id', $orderMaterialItemId)->update($omiData);
            }

//            $omInfo = $orderMaterialService->getInfoByOrderIdMaterialId(0, 0,'*',$omInfo['mid']);

            // 扣除条数(20200928修改为在 退料进度 确认退料后扣除条数)
            /* if ($omInfo && $omInfo['tiaoshu'] > 0) {
                $omData = [
                    'tiaoshu' => $omInfo['tiaoshu']-1,
                    'shiji_caigou_count' => $omInfo['tiaoshu']-1,
                    'tiaoshu_detail' => $omInfo['tiaoshu_detail'] . '-1',
                ];
                db('order_material')->where(['order_id' => $orderId, 'material_id' => $materialId])->update($omData);
            } */

            //同步到采购备忘
            $materialInfo = $materialService->getInfoById($materialId, 'name');
            $memoData = [
                'order_id' => 0,
                'client_ordernum' => '',
                'stock_m_type'=>1,
                'order_material_id'=>$omInfo['mid'],
                'content' => "物料[".$materialInfo['name']."]验布区布号[{$clothNum}]次品退料{$rejectsLength}米（".implode(',', $rejectsIds)."）",
                'status' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ];
            db('memo')->insertGetId($memoData);

            // 同步到退料进度表里
            $mrData = [
                'material_id' => $materialId,
                'order_id' => 0,
                'client_ordernum' => '',
                'stock_m_type' => 1,
                'order_material_id' => $omInfo['mid'],
                'order_material_item_id' => $orderMaterialItemId,
                'cloth_num' => $clothNum,
                'type' => 1,
                'reason' => implode(',', $rejectsIds), //$rejectsService->getNameStr($rejectsIds)
                'admin_id' => ADMIN_ID,
                'is_reduce' => 0,
                'status' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ];
            $materialReturnId = db('material_return')->insertGetId($mrData);

            // 记录退料操作日志
            (new MaterialReturnService())->addLog($materialReturnId, 1);

            // 更新布号米长
            $orderMaterialItemService->updateLength(0, 0, $omInfo['mid']);

            // 同步数据
            $checkclothShrinkService->syncData_stock_m_type_1($omInfo['mid'],0);

            $this->addOrderLog(0, '', $memoData['content'],['type'=>1,'order_material_id'=>$omInfo['mid']]);
            db()->commit();
            return $this->Json(1, '添加次品退料信息 ID' . $checkclothShrinkId . ' 成功');
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

	/**
	 * 获取今日验布记录
	 *
	 * @author KING
	 * @date 2020年4月24日
	 *
	 */
	public function todayLog() {
		$data = [];
		$page       = $this->request->param('page/d', 1);
		$limit      = $this->request->param('limit/d', 20);
		$dayStart = strtotime('0 day 00:00:00');
		$dayEnd = $dayStart + 86400;
		$where = [
			['type', '=', 1],
			['create_time', 'between', [$dayStart, $dayEnd]],
		];
		$list = db('checkcloth_shrink')->where($where)->page($page)->limit($limit)->order('id desc')->select();
		$data['count'] = db('checkcloth_shrink')->where($where)->count('id');

		$materialService = new MaterialService();
		$orderService = new OrderService();
		$n=0;
		foreach ($list as &$v) {
			$v['seq'] = $data['count']-($page-1)*$limit-$n;
			$mInfo = $materialService->getInfoById($v['material_id'], 'name');
			$v['material_name'] = $mInfo['name'];
            if ($v['stock_m_type'] == 0) {
                $oInfo = $orderService->getInfoById($v['order_id'], 'caichuang_type');
                $v['caichuang_type_text'] = arrayGet(config('mimo.caichuang_type'), $oInfo['caichuang_type'], '');
            }
			$n++;
		}

		$data['data'] = $list;
		$data['code'] = 0;
		$data['msg'] = '';
		return json($data);
	}

	/**
	 * 保存验布数据
	 *
	 * @author KING
	 * @date 2020年4月24日
	 *
	 */
	public function save() {
		$clientOrdernum = $this->request->param('client_ordernum/s', '');
		$materialId = $this->request->param('material_id/d', 0);
		$clothNum = $this->request->param('cloth_num/d', 0);
		$length = $this->request->param('length/d', 0);
		$trueFabricWidth = $this->request->param('true_fabric_width/d', 0);
        $info=db('order_material')->where('mid', substr($clientOrdernum, 1, 100))->find();
        if (substr($clientOrdernum, 0, 1) == 'B' && !empty($info['material_id']) ) { //是备料的验布
            return $this->saveV2_stock_m_type_1();
        }

		$orderService = new OrderService();
		$orderMaterialService = new OrderMaterialService();
		$orderMaterialItemService = new OrderMaterialItemService();
		$checkclothShrinkService = new CheckclothShrinkService();
		$orderInfo = $orderService->getInfoByClientOrdernum($clientOrdernum);

		// 判断是否少料
//    	$confirm = $this->request->param('confirm/d', 0);
//    	if (!$confirm) {
//	    	$lengthOverMessage = '';
//	    	if (db('order_material_item')->where("order_id = {$orderId} and material_id = {$materialId} and is_checkcloth = 0")->count() ==1 ) { // 最后一条布，才做提醒
//	    		$lengthNow = db('checkcloth_shrink')->where("order_id = {$orderId} and material_id = {$materialId} and type = 1 and is_return = 0")->sum("length");
//	    		$lengthNow += $length;
//	    		$caigouCount = $orderMaterialService->getNeedDosage($orderId, $materialId);//dump($lengthNow);dump($caigouCount);dump($lengthNow/$caigouCount);
//	    		if ($lengthNow/$caigouCount < 0.85 ) $lengthOverMessage = '少料，想要继续操作还需'.($caigouCount-$lengthNow).'米';
//
//	    		if ($lengthOverMessage != '') {
//	    			return $this->Json(-2, $lengthOverMessage);
//	    		}
//	    	}
//    	}

		if (!$orderInfo) {
			return $this->Json(0, '订单号不存在！');
		}
		$orderId = $orderInfo['id'];
		$systemUserKV = getSystemUserKV(null);
//		if($orderService->checkExceptionStatus($orderInfo['id'])) return $this->Json(0, "此单异常不允许操作，请找". arrayGet($systemUserKV,config('mp.order_exception_admin_id'),'邓昆明')."解决");//检查订单是否异常


		if (empty($materialId)) {
			return $this->Json(0, '未选择面料！');
		}

		if (empty($clothNum) || !is_numeric($clothNum)) {
			return$this->Json(0, '布号错误！');
		}

		if ($length == '' || !is_numeric($length)) {
			return$this->Json(0, '请填写验布米长！');
		}
		if ($trueFabricWidth == '' || !is_numeric($trueFabricWidth)) {
			return$this->Json(0, '请填写实量布封！');
		}

		$length = round(floatval($length), 2);
		$trueFabricWidth = round(floatval($trueFabricWidth), 2);
		if ($length > 300 || $length < 1) {
			return $this->Json(0, '验布米长范围只能是1-300！');
		}
		if ($trueFabricWidth > config('mp.fabric_width_max') || $trueFabricWidth < config('mp.fabric_width_min')) {
			return $this->Json(0, '实量布封范围只能是'.config('mp.fabric_width_min').'-'.config('mp.fabric_width_max').'！');
		}

		$rejectsIds = $this->request->param('rejects_id/a', []);
		$rejectsLength = floatval($this->request->param('rejects_length/d', 0));
		if (!is_numeric($rejectsLength)) {
			return $this->Json(0, '请填写次品米数！');
		}

		$omInfo = $orderMaterialService->getInfoByOrderIdMaterialId($orderId, $materialId);
		if (empty($omInfo)) {
			return $this->Json(0, '材料数据异常！');
		}

		$where = [
			['order_id', '=', $orderId],
			['material_id', '=', $materialId],
			['type', '=', 1],
			['cloth_num', '=', $clothNum],
			//['is_return', '=', 0],
		];
		$info = db('checkcloth_shrink')->where($where)->field("id")->findOrEmpty();
		if ($info) {
			return $this->Json(0, '该布号已处理！');
		} else {
			$orderMaterialItemId = $orderMaterialItemService->getIdByClothNum($orderId, $materialId, $clothNum);
			if (!$orderMaterialItemId) {
				return $this->Json(0, '布号数据错误！');
			}
			$omiInfo = $orderMaterialItemService->getInfoById($orderMaterialItemId);
            if ($omiInfo['flag_del'] == 1) {
                return $this->Json(0, '此布号已删除！');
            }
			try {
				db()->startTrans();

				$insData = [
					'order_id' => $orderId,
					'client_ordernum' => $orderInfo['client_ordernum'],
					'type' => 1,
					'order_material_item_id' => $orderMaterialItemId,
					'cloth_num' => $clothNum,
					'material_id' => $materialId,
					'stalls_id' => arrayGet($omiInfo, 'stalls_id', 0),
					'length' => round($length, 2),
					'true_fabric_width' => round($trueFabricWidth, 2),
					'admin_id' => ADMIN_ID,
					'is_rejects' => $rejectsLength > 0 ? 1 : 0,
					'rejects_ids' => $rejectsIds ? implode(',', $rejectsIds) : '',
					'rejects_length' => round($rejectsLength, 2),
					'create_time' => time(),
					'update_time' => time(),
				];
				$checkclothShrinkId = db('checkcloth_shrink')->insertGetId($insData);

				// 标记布号已验布
				if ($orderMaterialItemId) {
					$omiData = [
						'checkcloth_id' => $checkclothShrinkId,
						'is_checkcloth' => 1,
						'checkcloth_time' => time(),
						'update_time' => time()
					];
					db('order_material_item')->where('id', $orderMaterialItemId)->update($omiData);
				}

				// 更新布号米长
				$orderMaterialItemService->updateLength($orderId, $materialId);

				// 同步数据
				$checkclothShrinkService->syncData($orderId, $materialId,1);
                $orderMaterialService->updateCaichuangStatusV2($orderId, $omInfo['mid'], $this);
				$exception=0;$msg="";
				$dif=$orderMaterialService->checkClothLossStatus($omInfo['mid']);
				if ($dif) {
					$exception=1;//验布损耗大于0.06 true=1 ,false=0
					$msg="该单物料亏损严重，差异".$dif."米";
				}
				$this->addOrderLog($orderId, $orderInfo['client_ordernum'], "保存物料[".getMaterialName($materialId)."]布号{$clothNum}验布数据，验布记录ID {$checkclothShrinkId}");
				db()->commit();

				return $this->Json(1, '操作成功',['exception'=>$exception,'msg'=>$msg]);
			} catch (\Exception $e) {
				db()->rollback();
				return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
			}
		}

	}

    /**
     * 备料的验布完成
     * @param $omInfo
     * @param $param
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/20
     */
    private function saveV2_stock_m_type_1()
    {
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $materialId = $this->request->param('material_id/d', 0);
        $clothNum = $this->request->param('cloth_num/d', 0);
        $length = $this->request->param('length/d', 0);
        $trueFabricWidth = $this->request->param('true_fabric_width/d', 0);
        $rejectsIds = $this->request->param('rejects_id/a', []);
        $rejectsLength = floatval($this->request->param('rejects_length/d', 0));
        if (!is_numeric($rejectsLength)) {
            return $this->Json(0, '请填写次品米数！');
        }

        $orderService = new OrderService();
        $orderMaterialService = new OrderMaterialService();
        $orderMaterialItemService = new OrderMaterialItemService();
        $checkclothShrinkService = new CheckclothShrinkService();

        $omInfo = $orderMaterialService->getInfoById(substr($clientOrdernum, 1, 10));
        if (!$omInfo) {
            return $this->Json(0, '采购批号不存在！');
        }

        $where = [
            ['order_material_id', '=', $omInfo['mid']],
            ['stock_m_type', '=', 1],
            ['type', '=', 1],
            ['cloth_num', '=', $clothNum],
            //['is_return', '=', 0],
        ];
        $info = db('checkcloth_shrink')->where($where)->field("id")->findOrEmpty();
        if ($info) {
            return $this->Json(0, '该布号已处理！');
        } else {
            $orderMaterialItemId = $orderMaterialItemService->getIdByClothNum(0, 0, $clothNum, $omInfo['mid']);
            if (!$orderMaterialItemId) {
                return $this->Json(0, '布号数据错误！');
            }
            $omiInfo = $orderMaterialItemService->getInfoById($orderMaterialItemId);
            if ($omiInfo['flag_del'] == 1) {
                return $this->Json(0, '此布号已删除！');
            }
            try {
                db()->startTrans();

                $insData = [
                    'order_id' => 0,
                    'client_ordernum' => '',
                    'stock_m_type' => 1,
                    'order_material_id' => $omInfo['mid'],
                    'type' => 1,
                    'order_material_item_id' => $orderMaterialItemId,
                    'cloth_num' => $clothNum,
                    'material_id' => $omInfo['material_id'],
                    'stalls_id' => arrayGet($omiInfo, 'stalls_id', 0),
                    'length' => round($length, 2),
                    'true_fabric_width' => round($trueFabricWidth, 2),
                    'admin_id' => ADMIN_ID,
                    'is_rejects' => $rejectsLength > 0 ? 1 : 0,
                    'rejects_ids' => $rejectsIds ? implode(',', $rejectsIds) : '',
                    'rejects_length' => round($rejectsLength, 2),
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                $checkclothShrinkId = db('checkcloth_shrink')->insertGetId($insData);

                // 标记布号已验布
                if ($orderMaterialItemId) {
                    $omiData = [
                        'checkcloth_id' => $checkclothShrinkId,
                        'is_checkcloth' => 1,
                        'checkcloth_time' => time(),
                        'update_time' => time()
                    ];
                    db('order_material_item')->where('id', $orderMaterialItemId)->update($omiData);
                }

                // 更新布号米长
                $orderMaterialItemService->updateLength(0, 0, $omInfo['mid']);

                // 同步数据
                $checkclothShrinkService->syncData_stock_m_type_1($omInfo['mid'], 1);
                $orderMaterialService->updateCaichuangStatusV2(0, $omInfo['mid'], $this);
                $exception = 0;
                $msg = "";
                $dif = $orderMaterialService->checkClothLossStatus($omInfo['mid']);
                if ($dif) {
                    $exception = 1;//验布损耗大于0.06 true=1 ,false=0
                    $msg = "该单物料亏损严重，差异" . $dif . "米";
                }
                $this->addOrderLog(0, '', "保存物料[" . getMaterialName($omInfo['material_id']) . "]布号{$clothNum}验布数据，验布记录ID {$checkclothShrinkId}", ['type' => 1, 'order_material_id' => $omInfo['mid']]);
                db()->commit();

                return $this->Json(1, '操作成功', ['exception' => $exception, 'msg' => $msg]);
            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }
        }
    }

    /**
	 * 验布任务单
	 *
	 * @author KING
	 * @date 2020年5月26日
	 *
	 */
	public function task() {
		if ($this->request->isAjax()) {
			$clientOrdernum    = $this->request->param('client_ordernum/s');
			$createDateRange    = $this->request->param('create_time/s');
			$cloName    = $this->request->param('name/s');
			$startTime = strtotime(date("Y-m-d 00:00:00"));
			$endTime = $startTime+86400-1;

			$lastUpdateTime = $this->request->param('update_time/d', 0);
			$dbUpdateTime = db('order_material_item')->order('update_time desc')->value('update_time');
			if ($dbUpdateTime && $dbUpdateTime == $lastUpdateTime && !isset($clientOrdernum)) {
				return $this->Json(0, "数据无变更！", ['update_time' => $dbUpdateTime]);
			}

			$checkclothShrinkService = new CheckclothShrinkService();

			// 未完成任务列表
			$whereBefore=$where=[];
			$whereBefore[]=$where[]=['o.status' , '<>' ,99];
			if ($clientOrdernum != '') {
    			$whereBefore[] = ['o.client_ordernum','like', "%".$clientOrdernum."%"];
    		}
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    if ($ext_id != '') {
                        $temp = db('order')->field('id')->where([['ext_id', '=', $ext_id]])->find();
                        $whereBefore[] = ['o.id', '=', $temp['id']];
                    }
                    break;
            }
            //订单加一级
            order_level($whereBefore,'o.');
			if ($cloName != '') {
    			$whereBefore[] = ['m.name','like', "%".$cloName."%"];
    		}
			if ($createDateRange != '') {
				list($startT, $endT) = array_map('strtotime', explode('~', $createDateRange));
				$whereBefore[] = ['omi.create_time', 'between', [$startT, $endT+86399]];
			}
			$whereBefore[] =['omi.need_checkcloth', '=', 1];
			$whereBefore[] =['omi.is_checkcloth', '=', 0];
			$field = "o.shipment_time,o.client_ordernum,om.tiaoshu,om.caigou_status,omi.cloth_num,m.name,m.color,omi.create_time,m.id as mid";
			$todoList = db('order_material_item omi')
			->join('order o', 'o.id = omi.order_id')
			->join('material m', 'm.id = omi.material_id')
			->join('order_material om', 'om.mid = omi.order_material_id')
			->where($whereBefore)->order('o.shipment_time asc,omi.id asc')->field($field)->select();
			foreach ($todoList as $k => $v) {
				$todoList[$k]['type_name'] = '验布';
				$todoList[$k]['caigou_status_text'] = $v['caigou_status'] ? '是' : '否';
				$todoList[$k]['shipment_time'] = date('n月j日', $v['shipment_time']);
				$todoList[$k]['create_time'] = date('n月j日', $v['create_time']);
			}
			// 已完成任务列表
			$where = [
				['omi.need_checkcloth', '=', 1],
				['omi.is_checkcloth', '=', 1],
				['omi.is_return', '=', 0],
				['omi.checkcloth_time', 'between', [$startTime, $endTime]],
			];
            //订单加一级
            order_level($where,'o.');
			$field = "m.need_checkcloth,o.shipment_time,o.client_ordernum,om.tiaoshu,om.caigou_status,omi.cloth_num,m.name,m.color,omi.create_time,omi.checkcloth_time as over_time,omi.is_return,cs.true_fabric_width,cs.length,cs.true_weight";
			$doneList = db('order_material_item omi')
			->join('order o', 'o.id = omi.order_id')
			->join('material m', 'm.id = omi.material_id')
			->join('order_material om', 'om.mid = omi.order_material_id')
			->join('checkcloth_shrink cs', 'cs.id = omi.checkcloth_id')
			->where($where)->order('omi.checkcloth_time desc')->field($field)->select();
			foreach ($doneList as $k => $v) {
				$doneList[$k]['type_name'] = '验布'.($v['is_return']?'/退料':'');
				$doneList[$k]['shipment_time'] = date('n月j日', $v['shipment_time']);
				$doneList[$k]['create_time'] = date('n月j日', $v['create_time']);
				$doneList[$k]['over_time'] = date('n月j日', $v['over_time']);
				$doneList[$k]['caigou_status_text'] = $v['caigou_status'] ? '是' : '否';
			}

			// 统计（待处理，当日完成率，预计完成时间，当日来料总数，上月未完成总数）
			$todoNum = count($todoList);	// 待处理
			$todayOverRate = '100%';	// 今日完成率
			$planOverTime = '';	// 预计完成时间
			$todayTotalNum = 0;	// 今日来料总数

			$monthTotalNum = 0;	// 本月来料总数
			$lastMonthTodoTotalNum = 0;	// 上月未完成总数
			$thisMonthTodoTotalNum = 0;	// 本月未完成总数

			// 今日完成率
			$todayOverNum = count($doneList);	// 今日完成数
			if ($todayOverNum+$todoNum > 0) {
				$todayOverRate = round($todayOverNum*100/($todayOverNum+$todoNum), 2) . '%';
			}

			$lastMonthStart = strtotime(date('Y-m-01 00:00:00', strtotime('-1 month')));
			$lastMonthEnd = strtotime(date("Y-m-1 00:00:00"))-1;
			$monthStart = strtotime(date("Y-m-1 00:00:00"));

			// 今日来料总数
			$where = [
				['need_checkcloth', '=', 1],
				['create_time', 'between', [$startTime, $endTime]],
			];
			$todayTotalNum = db('order_material_item')->where($where)->count(1);

			// 本月来料总数
                        $monthTotalNum = Db::query("SELECT COUNT(1) AS tp_count FROM `wx_order_material_item` WHERE  ( `need_checkcloth` = 0 OR `need_shrink` = 0 or `need_checkcloth` = 1 OR `need_shrink` = 1 )  AND `create_time` >= $monthStart");
			$monthTotalNum = $monthTotalNum[0]['tp_count'];
                        //dump($monthTotalNum);
			// 上月未完成总数
			$where = [
				['create_time', 'between', [$lastMonthStart, $lastMonthEnd]],
			];
			$lastMonthTodoTotalNum = db('order_material_item')->where('need_checkcloth = 1 and is_checkcloth = 0 or need_shrink = 1 and is_shrink = 0')->where($where)->count(1);

			// 本月未完成总数
			$where = [
				['create_time', '>=', $monthStart],
			];
			$thisMonthTodoTotalNum = db('order_material_item')->where('need_checkcloth = 1 and is_checkcloth = 0 or need_shrink = 1 and is_shrink = 0')->where($where)->count(1);

			// 预计完成时间
			$planOverTime = $checkclothShrinkService->calPlanOverTime(1, $todoNum);

			$d = [
				'todayOverNum' => $todayOverNum,
				'todoList' => $todoList,
				'doneList' => $doneList,
				'todoNum' => $todoNum,
				'todayOverRate' => $todayOverRate,
				'planOverTime' => $planOverTime,
				'monthTotalNum' => $monthTotalNum,
				'todayTotalNum' => $todayTotalNum,
				'lastMonthTodoTotalNum' => $lastMonthTodoTotalNum,
				'thisMonthTodoTotalNum' => $thisMonthTodoTotalNum,
				'updateTime' => $dbUpdateTime
			];
			return $this->Json(1, '获取成功！', $d);
		}
		return $this->assign([])->fetch();
	}

	/**
	 * 验布任务详情（已完成）
	 *
	 * @author KING
	 * @date 2020年5月26日
	 *
	 */
	public function taskDetail() {
		$systemUserKV = getSystemUserKV(null);
		if ($this->request->isAjax()) {
			$s = microtime(true);
			$page       = $this->request->param('page/d', 1);
			$limit      = $this->request->param('limit/d', 20);
			$adminId      = $this->request->param('admin_id/d', 0);

			$where = [
				['o.status', 'in', [0, 1]],
				['cs.type', '=', 1]
			];
			if ($adminId) {
				$where[] = ['cs.admin_id', '=', $adminId];
			}
			$field = "cs.*,o.factory_id,o.sku,o.group_id,o.client_ordernum,o.shipment_time,o.sku,m.name material_name,m.color,omi.create_time as come_time,om.tiaoshu";
			$order = "cs.id desc";
			$count = db('checkcloth_shrink cs')
			->join('order o', 'o.id = cs.order_id')
			->join('material m', 'm.id = cs.material_id')
			->where($where)->count();


			$list = db('checkcloth_shrink cs')
			->join('order o', 'o.id = cs.order_id')
			->join('material m', 'm.id = cs.material_id')
			->join('order_material_item omi', 'omi.id = cs.order_material_item_id')
			->join('order_material om', 'omi.order_material_id = om.mid')
			->where($where)->field($field)->order($order)->page($page)->limit($limit)->select();

			foreach ($list as $k => $v) {
				$v['type_text'] = '验布' . ($v['is_return'] ? '/退料' : '');
				$v['shipment_time_text'] = $v['shipment_time'] ? date('Y-m-d H:i', $v['shipment_time']) : '';
				$v['create_time_text'] = $v['create_time'] ? date('Y-m-d H:i', $v['create_time']) : '';
				$v['come_time_text'] = $v['come_time'] ? date('Y-m-d H:i', $v['come_time']) : '';

				$v['tiaoshu'] = $v['tiaoshu'];
				$v['true_weight'] = 0;
				if ($v['type'] == 2 && $v['length_shrink'] > 0 && $v['fabric_width_shrink'] > 0) {
					$v['true_weight'] = round(($v['weight_shrink'] - $v['weight_page']) * 1000 / ($v['length_shrink'] * $v['fabric_width_shrink'] / 100), 2);
				}

				if ($v['type'] == 1) {
					$v['weight_shrink'] = '';
					$v['weight_page'] = '';
					$v['true_weight'] = '';
				}

				$v['is_return_text'] = $v['is_return']?'是':'否';

				$list[$k] = $v;
			}

			$data['data'] = $list;
			$data['count'] = $count;
			$data['code'] = 0;
			$data['msg'] = '';
			$e = microtime(true);
			$data['cost'] = $e-$s;
			return json($data);
		}
		$assign = [
			'userList' => db('checkcloth_shrink cs')->join('system_user su', 'cs.admin_id = su.id')->where('type', 1)->distinct(true)->field('cs.admin_id')->column('su.nick','cs.admin_id'),
		];
		return $this->assign($assign)->fetch();
	}

}

